﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using MES.DataGateway.Presenter;
using MES.DataGateway.Common;
using System.IO;
using System.Windows.Forms;
using System.Configuration;

namespace MES.DataGateway.Service
{
    public partial class DataGatwayService : ServiceBase
    {
        public DataGatwayService()
        {
            InitializeComponent();
        }


        private System.Timers.Timer  m_SyncTimer;
        private DataGatwayPresenter presenter = null;

        protected override void OnStart(string[] args)
        {            
            CreateLog();
            m_SyncTimer = new System.Timers.Timer();
            m_SyncTimer.Enabled = false;
            m_SyncTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_SyncTimer_Elapsed);

            int intSync = Convert.ToInt32(ConfigurationManager.AppSettings["sync"]);
            m_SyncTimer.Interval = intSync * 10 * 1000;

            presenter = new DataGatwayPresenter();
            m_SyncTimer.Start();
        }

        void m_SyncTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                m_SyncTimer.Enabled = false;
                presenter.RunService();
                m_SyncTimer.Enabled = true;
            }
            catch (Exception myError)
            {
                Log.WriteLog(DateTime.Now.ToString(), 1, "未能正确获取数据导入文件," + myError.Message);
            }
            finally
            {
                m_SyncTimer.Enabled = true;
            }
        }

        protected override void OnStop()
        {

        }


        #region 创建日志文件
        private void CreateLog()
        {
            string strFileName = Application.StartupPath + "\\Log\\" + "log_" + DateTime.Now.ToString("yyyyMMdd") + ".xml";
            if (File.Exists(strFileName) == false)
            {
                Log.CreateLogFile();
            }
        }
        #endregion
    }
}
